package com.bpzj.util.advice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.file.AccessDeniedException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author bpzj 2019/11/19 16:02
 */
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class CommonControllerAdvice {

  @ResponseBody
  @ExceptionHandler(value = {Exception.class, BusinessException.class})
  public Map errorHandler(Exception ex) {
    if (ex instanceof BusinessException) {
      log.info("[业务异常]");
      // return
    }
    Map<String,Object> map = new HashMap();
    map.put("code", 100);
    map.put("msg", ex.getMessage());
    if (ex instanceof HttpMessageNotReadableException) {
      map = new HashMap<>();
      map.put("code", 100);
      map.put("msg", "something error");
    }
    if (ex instanceof AccessDeniedException) {
      map = new HashMap<>();
      map.put("code", 100);
      map.put("msg", "权限异常");
    }
    // if (ex instanceof ConstraintViolationException) {
    //   map = new HashMap<>();
    //   map.put("code", 100);
    //   map.put("msg", "参数错误");
    // }

    return map;
  }
}
